<!--
 * @Author: yanzengyong 709402944@qq.com
 * @Date: 2025-08-14 10:51:59
 * @LastEditors: yanzengyong 709402944@qq.com
 * @LastEditTime: 2025-08-18 20:18:37
 * @FilePath: /cyj-boot-parent/cyj-boot-web/src/views/demo/pure/MultipleFormInpExample/index.vue
 * @Description: 这是默认设置,请设置`customMade`, 打开koroFileHeader查看配置 进行设置: https://github.com/OBKoro1/koro1FileHeader/wiki/%E9%85%8D%E7%BD%AE
-->
<template>
  <div class="pure-container">
    <div class="form-container">
      <a-form :model="formState" name="basic" layout="inline" :label-col="{ span: 8 }" :wrapper-col="{ span: 16 }" @submit="onSubmit">
        <a-form-item label="字典名称:" name="name">
          <a-input v-model:value="formState.name" placeholder="请输入字典名称" />
        </a-form-item>

        <a-form-item label="字段编码:" name="code">
          <a-input v-model:value="formState.code" placeholder="请输入字段编码" />
        </a-form-item>

        <a-form-item :wrapper-col="{ offset: 2, span: 16 }">
          <a-space>
            <a-button type="primary" html-type="submit">查询</a-button>
            <a-button @click="resetForm">重置</a-button>
          </a-space>
        </a-form-item>
      </a-form>
    </div>
    <div class="table-container">
      <a-table
        ref="tableElRef"
        :pagination="pagination"
        @change="handleTableChange"
        :columns="columns"
        :data-source="data"
        :row-selection="{
          selectedRowKeys,
          onChange: onSelectChange,
        }"
        :loading="loading"
        :scroll="table_scroll"
        rowKey="id"
        bordered
      >
        <template #title>
          <div class="flex items-center cyj-basic-table-header__table-title-box">
            <div class="cyj-basic-table-header__tableTitle">
              <a-button type="primary" preIcon="ant-design:plus-outlined" @click="handleCreate"> 新增</a-button>
              <a-button preIcon="ant-design:sync-outlined" @click="handleRefreshCache">刷新缓存</a-button>

              <a-dropdown v-if="hasSelected">
                <template #overlay>
                  <a-menu>
                    <a-menu-item key="1" @click="batchHandleDelete">
                      <Icon icon="ant-design:delete-outlined" />
                      删除
                    </a-menu-item>
                  </a-menu>
                </template>
                <a-button
                  >批量操作
                  <Icon icon="ant-design:down-outlined" />
                </a-button>
              </a-dropdown>
            </div>

            <div class="cyj-basic-table-header__toolbar"> </div>
          </div>
          <div class="info-box">
            <a-alert type="info" show-icon class="alert">
              <template #message>
                <template v-if="hasSelected">
                  <span>
                    <span>已选中 {{ selectedRowKeys.length }} 条记录</span>
                  </span>
                  <a-divider type="vertical" />
                  <a @click="setSelectedRowKeys([])">清空</a>
                </template>
                <template v-else>
                  <span>未选中任何数据</span>
                </template>
              </template>
            </a-alert>
          </div>
        </template>
        <template #emptyText>
          <div class="empty-box">
            <img :src="noDataPng" alt="" />
            <div>暂无数据</div>
          </div>
        </template>
        <!--操作栏-->
        <template #operation="{ record }">
          <PopConfirmButton :enable="false" type="link" size="small" color="success" @click="handleEdit(record)" label="编辑">
            编辑
          </PopConfirmButton>
          <Divider type="vertical" class="action-divider" />
          <PopConfirmButton
            overlayClassName="cyj-basic-table-action-popconfirm"
            type="link"
            size="small"
            color="error"
            title="确定删除吗?"
            @confirm="deleteConfirm(record)"
            label="删除"
          >
            删除
          </PopConfirmButton>
        </template>
      </a-table>
    </div>
  </div>
  <createDialog @register="registerModal" />
</template>

<script setup lang="ts">
  import noDataPng from '/@/assets/images/table_nodata.png';
  import { ref, reactive, computed, onMounted, unref, nextTick } from 'vue';
  import { Divider } from 'ant-design-vue';
  import { PopConfirmButton } from '/@/components/Button';
  import { useModal } from '/@/components/Modal';
  import createDialog from './createDialog.vue';
  import { getList_Mock } from './utils';
  import { useMessage } from '/@/hooks/web/useMessage';
  import { useWindowSizeFn } from '/@/hooks/event/useWindowSizeFn';

  /**计算表格滚动的动态高度 */
  const tableElRef = ref(null);

  const table_scroll = ref({
    x: true,
    y: 600,
  });

  const calcTableHeight = () => {
    const table = unref(tableElRef);
    if (!table) return;
    const tableEl: Element = table.$el;

    const titleEl = tableEl.querySelector('.ant-table-title') as HTMLElement;
    const tableContainerEl = tableEl.querySelector('.ant-table') as HTMLElement;
    const headEl = tableEl.querySelector('.ant-table-thead') as HTMLElement;
    let tableHeight = 0;
    let titleHeight = 0;
    let headHeight = 0;

    if (titleEl) {
      titleHeight = titleEl.offsetHeight;
      console.log('titleHeight=====', titleHeight);
    }
    if (tableContainerEl) {
      tableHeight = tableContainerEl.offsetHeight;
      console.log('tableHeight=====', tableHeight);
    }
    if (headEl) {
      headHeight = headEl.offsetHeight;
      console.log('headHeight=====', headHeight);
    }

    const y = tableHeight - titleHeight - headHeight;

    console.log('y=====', y);
    table_scroll.value.y = y;
  };

  useWindowSizeFn(calcTableHeight, 280);
  /**计算表格滚动的动态高度 */

  const $message = useMessage();

  //字典model
  const [registerModal, { openModal }] = useModal();

  /**表单查询 */
  interface FormState {
    name: string;
    code: string;
  }

  const formState = reactive<FormState>({
    name: '',
    code: '',
  });

  const resetForm = () => {
    console.log('Success:');
    formState.name = '';
    formState.code = '';
    pagination.current = 1;
    pagination.pageSize = 10;
    getList();
  };

  const handleRefreshCache = () => {
    getList();
  };

  const onSubmit = () => {
    getList();
  };

  const handleEdit = (record) => {
    console.log('handleEdit----', record);
  };

  // 删除确认
  const deleteConfirm = (record) => {
    console.log('deleteConfirm----', record);
    $message.createMessage.success('删除成功！');
    getList();
  };
  /**表单查询 */

  const handleCreate = () => {
    console.log('handleCreate');
    openModal(true, {
      isUpdate: false,
      showFooter: true,
      tilte: '列表示例新增',
    });
  };

  const batchHandleDelete = () => {
    console.log('batchHandleDelete');
  };

  const columns = ref([
    {
      title: '项目名称',
      dataIndex: 'projectName',
    },
    {
      title: '实施阶段',
      dataIndex: 'implementationStage',
    },
    {
      title: '项目类型',
      dataIndex: 'projectType',
    },
    {
      title: '项目实施单位',
      dataIndex: 'projectImplementationUnit',
    },
    {
      title: '项目地点',
      dataIndex: 'projectLocation',
    },
    {
      title: '项目经理',
      dataIndex: 'projectManager',
    },
    {
      title: '检查牵头部门',
      dataIndex: 'inspectionLeadDepartment',
    },
    {
      title: '计划检查开始时间',
      dataIndex: 'plannedInspectionStartTime',
    },
    {
      title: '计划检查结束时间',
      dataIndex: 'plannedInspectionEndTime',
    },
    {
      title: '操作',
      dataIndex: 'operation',
      slots: { customRender: 'operation' },
      width: 130,
    },
  ]);

  interface listItem {
    id: string;
    projectName: string;
    implementationStage: string;
    projectType: string;
    projectImplementationUnit: string;
    projectLocation: string;
    projectManager: string;
    inspectionLeadDepartment: string;
    plannedInspectionStartTime: string;
    plannedInspectionEndTime: string;
  }

  const data = ref<listItem[]>([]);

  /**列表数据 */
  const pagination = reactive({
    current: 1,
    pageSize: 10,
    total: 0,
    showSizeChanger: true,
    pageSizeOptions: ['10', '20', '50', '100'],
    showQuickJumper: true,
    showTotal: (total) => `共 ${total} 条`,
    size: 'small',
  });

  const loading = ref<boolean>(false);

  const getList = async () => {
    loading.value = true;
    try {
      const res = await getList_Mock({
        column: 'createTime',
        order: 'desc',
        pageNo: pagination.current,
        pageSize: pagination.pageSize,
        dictName: formState.name,
        dictCode: formState.code,
      });
      console.log('res-------', res);
      data.value = res as listItem[];
    } finally {
      loading.value = false;
    }
  };

  onMounted(async () => {
    await nextTick();
    calcTableHeight();
    getList();
  });

  // 表格变化处理（分页、排序）
  const handleTableChange = (pag) => {
    pagination.current = pag.current;
    pagination.pageSize = pag.pageSize;
    getList();
  };
  /**列表数据 */

  /**列表选中相关内容 */
  type Key = string | number;
  const selectedRowKeys = ref<Key[]>([]);

  const hasSelected = computed(() => selectedRowKeys.value.length > 0);

  // 列表选择change事件
  const onSelectChange = (newSelectedRowKeys: Key[]) => {
    selectedRowKeys.value = newSelectedRowKeys;
  };

  // 快捷设置列表选中值
  const setSelectedRowKeys = (keys: Key[]) => {
    selectedRowKeys.value = keys;
  };
  /**列表选中相关内容 */
</script>

<style scoped lang="less">
  .pure-container {
    height: 100%;
    width: 100%;
    .form-container {
      width: 100%;
      height: 56px;
      background-color: #fff;
      border-radius: 8px;
      margin-bottom: 8px;
      padding: 12px;
      box-sizing: border-box;
    }
    .table-container {
      width: 100%;
      height: calc(100% - 64px);
      background-color: #fff;
      border-radius: 8px;
      .cyj-basic-table-header__tableTitle > * {
        margin-right: 12px;
      }
      .info-box {
        margin-top: 8px;
        .alert {
          height: 38px;
        }
      }
    }
  }
  :deep(.ant-divider-vertical) {
    margin: 0 2px;
  }
  :deep(.ant-table-title) {
    padding: 12px;
    box-sizing: border-box;
    border: none !important;
  }
  :deep(.ant-form) {
    height: 32px;
  }
  :deep(.ant-form-item) {
    display: flex;
    align-items: center;
    justify-content: flex-start;
    height: 100%;
    margin-inline-end: inherit;
  }
  :deep(.ant-pagination) {
    width: 100%;
    display: flex;
    align-items: center;
    justify-content: flex-end;
    margin: 0 !important;
    padding: 14px 20px;
    box-sizing: border-box;
    box-shadow: 0 -4px 8px rgba(0, 0, 0, 0.1);
  }
  :deep(.ant-table-wrapper) {
    height: 100%;
  }
  :deep(.ant-spin-nested-loading) {
    height: 100%;
  }
  :deep(.ant-spin-container) {
    height: 100%;
    display: flex;
    flex-direction: column;
    align-items: center;
    justify-content: space-between;
  }
  :deep(.ant-table) {
    width: 100%;
    height: calc(100% - 52px);
  }
</style>
